package com.demo.main.servlet;

import com.demo.main.entity.User;
import com.demo.main.service.UserService;
import com.demo.main.utils.ServletUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.demo.main.utils.ServletUtil.PERMISSION_PATH_PUBLIC;

@WebServlet({PERMISSION_PATH_PUBLIC + "/login",
        PERMISSION_PATH_PUBLIC + "/register",
        PERMISSION_PATH_PUBLIC + "/logout",
        PERMISSION_PATH_PUBLIC + "/validate"})
public class AuthenticationServlet extends HttpServlet {

    private final UserService userService = new UserService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        ServletUtil servletUtil = new ServletUtil(request, response);

        if (!request.getServletPath().equals(PERMISSION_PATH_PUBLIC + "/register")) {
            String code = request.getParameter("code");
            String randStr = servletUtil.getSessionAttribute("randStr", String.class);
            if (!code.equalsIgnoreCase(randStr)) {
                servletUtil.removeSessionAttribute("randStr");
                servletUtil.redirectToLogin();
                return;
            }
        }

        switch (request.getServletPath()) {
            case PERMISSION_PATH_PUBLIC + "/login":
                User user = servletUtil.convertRequestParameter(User.class);
                if (userService.login(user)) {
                    User loginUser = userService.findOneByCondition(user);
                    servletUtil.loginAndRedirectToHomeViewByCurrentRole(loginUser.getUserId(), loginUser.getUsername(), loginUser.getRole());
                    break;
                }
                servletUtil.redirectToLogin();
                break;
            case PERMISSION_PATH_PUBLIC + "/register":
                user = servletUtil.convertRequestParameter(User.class);
                user.setRole("user");
                userService.addOne(user);
                servletUtil.redirectToLogin();
                break;
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        ServletUtil servletUtil = new ServletUtil(request, response);

        switch (request.getServletPath()) {
            case PERMISSION_PATH_PUBLIC + "/logout":
                servletUtil.logoutAndRedirectToLoginView();
                break;
            case PERMISSION_PATH_PUBLIC + "/validate":
                servletUtil.forward("/WEB-INF/common/validate.jsp");
                break;
        }
    }
}
